package guoanmaker.operator.business.service;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.transaction.Transactional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import guoanmaker.operator.business.model.MessageType;
import guoanmaker.operator.business.model.OperatorRefuseRecord;
import guoanmaker.operator.business.model.OperatorRefuselist;
import guoanmaker.operator.business.model.OperatorUser;
import guoanmaker.operator.business.model.ProvideRoom;
import guoanmaker.operator.business.model.ProvideSpacefacilities;
import guoanmaker.operator.business.modelnobind.ProvideRoomMove;
import guoanmaker.operator.business.repository.MessageTypeRepository;
import guoanmaker.operator.business.repository.OperatorRefuseRecordRepository;
import guoanmaker.operator.business.repository.OperatorRefuselistRepository;
import guoanmaker.operator.business.repository.OperatorRoomRepository;
import guoanmaker.operator.business.repository.OperatorUserRepository;
import guoanmaker.operator.business.repository.ProvideSpacefacilitiesRepository;


@Service
public class OperatorRoomService implements OperatorRoomServiceInterface {
	
	@PersistenceContext
	private EntityManager manager;
	
	@Autowired
	private OperatorRoomRepository operatorRoomRepository;
	
	@Autowired
	private MessageTypeRepository messageTypeRepository;
	
	@Autowired
	private OperatorUserRepository operatorUserRepository;
	
	@Autowired
	private OperatorRefuseRecordRepository operatorRefuseRecordRepository;
	
	@Autowired
	private OperatorRefuselistRepository operatorRefuselistRepository;
	
	@Autowired
	private ProvideSpacefacilitiesRepository provideSpacefacilitiesRepository;
	
	@Override
	public Map<String, Object> selectRoomListByStauts(Integer roomState, Integer page, Integer size) {
		Map<String,Object> map=new HashMap<String,Object>();
		String jpql="select new guoanmaker.operator.business.modelnobind.ProvideRoomMove(rm.id,rm.roomName,rm.roomCodes,b.companyName,b.commoditys,"
				+ "user.username,rm.roomTime) "
				+ "from ProvideRoom rm left join rm.providerBusiness b left join b.personalUser user where ";
		
		if(roomState==10){
			jpql+=" rm.roomState in (4,5) order by rm.roomTime desc";
		}
		else{
			jpql+=" rm.roomState=:roomState order by rm.roomTime desc";
		}
		Query query = manager.createQuery(jpql);
		if(roomState!=10){
			query.setParameter("roomState", roomState);
		}
		int count=query.getResultList().size();
		List<ProvideRoomMove> list=query.setMaxResults(size)
				.setFirstResult(page*size)
				.getResultList();
		if(roomState!=1){
			for(int i=0;i<list.size();i++){
				ProvideRoomMove p=list.get(i);
				String roomId=p.getId();
				String jpqls="select new guoanmaker.operator.business.model.OperatorRefuseRecord(orf.refuseTime) "
						+ "from OperatorRefuseRecord orf where orf.attributId=:roomId order by orf.refuseTime desc";
				Query querys = manager.createQuery(jpqls).setParameter("roomId", roomId).setMaxResults(1).setFirstResult(0);
				List<OperatorRefuseRecord> lists=querys.getResultList();
				if(lists!=null&&lists.size()>0){
					OperatorRefuseRecord op=lists.get(0);
					p.setDotime(op.getRefuseTime());
					list.remove(i);
					list.add(i, p);
				}
				
			}
		}
		map.put("count", count);
		map.put("list", list);
		return map;
	}

	@Override
	public ProvideRoomMove selectRoomByRoomId(String roomId) {
		String jpql="select new guoanmaker.operator.business.modelnobind.ProvideRoomMove(rm.id,rm.describeAsk,rm.roomName,rm.roomCodes,rm.city.name,rm.area.name,rm.province.name,"
				+ "rm.address,rm.complement,rm.roomlogo,rm.spaceDetail,rm.complement,rm.roomImgOne,rm.roomImgTwo,rm.roomImgThree,rm.roomImgFour,rm.roomImgFive,"
				+ "rm.roomTime) from ProvideRoom rm where rm.id=:roomId";
		Query query = manager.createQuery(jpql).setParameter("roomId", roomId);
		List<ProvideRoomMove> list=query.getResultList();
		ProvideRoomMove provideRoomMove=null;
		if(list!=null&&list.size()>0){
			provideRoomMove=list.get(0);
		}
		return provideRoomMove;
	}

	@Override
	public List<OperatorRefuseRecord> selectRefuseBYRoomId(String roomId) {
		String jpql="select new guoanmaker.operator.business.model.OperatorRefuseRecord(orf.content,orf.reasonName,orf.useraccountforcord,orf.status,orf.refuseTime) "
				+ "from OperatorRefuseRecord orf where orf.attributId=:roomId";
		Query query = manager.createQuery(jpql).setParameter("roomId", roomId);
		List<OperatorRefuseRecord> list=query.getResultList();
		return list;
	}

	@Transactional
	public int roomConsentAudit(String roomId, String userId) {
		OperatorUser operatorUser=operatorUserRepository.findOne(userId);
		OperatorRefuseRecord operatorRefuseRecord=new OperatorRefuseRecord();
		operatorRefuseRecord.setAttributId(roomId);
		operatorRefuseRecord.setUseraccountforcord(operatorUser.getUsername()+"-审核通过");
		operatorRefuseRecord.setStatus(1);
		operatorRefuseRecord.setOpchannel(3);
		operatorRefuseRecord.setRefuseTime(new Date());
		operatorRefuseRecordRepository.save(operatorRefuseRecord);
		String jpql = "UPDATE ProvideRoom p set p.roomState=2 where p.id =:roomId"; 
		Query query = manager.createQuery(jpql); 
		query.setParameter("roomId",roomId); 
		int a=query.executeUpdate();
		ProvideRoom operatorRoom=operatorRoomRepository.findOne(roomId);
		MessageType messageType=new MessageType();
		messageType.setSourceid(roomId);
		messageType.setCreatedate(new Date());
		messageType.setDecribestr("您有一个<b>【"+operatorRoom.getRoomName()+"】</b>空间审核已通过");
		messageType.setIsread(0);
		messageType.setType(6);
		messageType.setBusinessid(operatorRoom.getProviderBusiness().getId());
		messageTypeRepository.save(messageType);
		return a;
	}

	@Override
	public List<OperatorRefuselist> selectOperatorRefuselist() {
		return operatorRefuselistRepository.selectByAttribution(5);
	}

	@Transactional
	public int RefuseRoomApplication(String reasonName,String content, String userId,String roomId) {
		OperatorUser operatorUser=operatorUserRepository.findOne(userId);
		OperatorRefuseRecord operatorRefuseRecord=new OperatorRefuseRecord();
		operatorRefuseRecord.setAttributId(roomId);
		operatorRefuseRecord.setContent(content);
		operatorRefuseRecord.setReasonName(reasonName);
		operatorRefuseRecord.setUseraccountforcord(operatorUser.getUsername()+"-拒绝");
		operatorRefuseRecord.setStatus(2);
		operatorRefuseRecord.setOpchannel(3);
		operatorRefuseRecord.setRefuseTime(new Date());
		operatorRefuseRecordRepository.save(operatorRefuseRecord);
		String jpql = "UPDATE ProvideRoom p set p.roomState=3,p.auditOpinion=:auditOpinion,p.roomUnread=0 where p.id =:roomId"; 
		Query query = manager.createQuery(jpql); 
		query.setParameter("roomId",roomId); 
		query.setParameter("auditOpinion",reasonName); 
		int a=query.executeUpdate();
		ProvideRoom operatorRoom=operatorRoomRepository.findOne(roomId);
		MessageType messageType=new MessageType();
		messageType.setSourceid(roomId);
		messageType.setCreatedate(new Date());
		messageType.setDecribestr("您有一个【"+operatorRoom.getRoomName()+"】空间审核未通过");
		messageType.setIsread(0);
		messageType.setType(6);
		messageType.setBusinessid(operatorRoom.getProviderBusiness().getId());
		messageTypeRepository.save(messageType);
		return a;
	}

	@Transactional
	public int CloseRoomAudit(String reasonName, String content, String userId, String roomId) {
		// TODO Auto-generated method stub
		OperatorUser operatorUser=operatorUserRepository.findOne(userId);
		OperatorRefuseRecord operatorRefuseRecord=new OperatorRefuseRecord();
		operatorRefuseRecord.setAttributId(roomId);
		operatorRefuseRecord.setContent(content);
		operatorRefuseRecord.setReasonName(reasonName);
		operatorRefuseRecord.setUseraccountforcord(operatorUser.getUsername()+"-关闭");
		operatorRefuseRecord.setStatus(3);
		operatorRefuseRecord.setOpchannel(3);
		operatorRefuseRecord.setRefuseTime(new Date());
		operatorRefuseRecordRepository.save(operatorRefuseRecord);
		String jpql = "UPDATE ProvideRoom p set p.roomState=5,p.violationReasons=:violationReasons,p.roomUnread=0 where p.id =:roomId"; 
		Query query = manager.createQuery(jpql); 
		query.setParameter("roomId",roomId); 
		query.setParameter("violationReasons",reasonName); 
		int a=query.executeUpdate();
		ProvideRoom operatorRoom=operatorRoomRepository.findOne(roomId);
		MessageType messageType=new MessageType();
		messageType.setSourceid(roomId);
		messageType.setCreatedate(new Date());
		messageType.setDecribestr("您有一个【"+operatorRoom.getRoomName()+"】空间审核已违规");
		messageType.setIsread(0);
		messageType.setType(6);
		messageType.setBusinessid(operatorRoom.getProviderBusiness().getId());
		messageTypeRepository.save(messageType);
		return a;
	}

	public OperatorRefuselist insertRoomRefuselist(String categoryName, String userId) {
		OperatorRefuselist operatorRefuse= operatorRefuselistRepository.selectByCategoryNameRoom(categoryName);
		if(operatorRefuse!=null){
			return null;
		}
		OperatorUser operatorUser=operatorUserRepository.findOne(userId);
		OperatorRefuselist operatorRefuselist=new OperatorRefuselist();
		operatorRefuselist.setAttribution(5);
		operatorRefuselist.setCategoryName(categoryName);
		operatorRefuselist.setCreateDate(new Date());
		operatorRefuselist.setCreateUser(operatorUser.getUsername());
		return operatorRefuselistRepository.save(operatorRefuselist);
	}

	@Transactional
	public void deleteRoomRefuselist(String refuseId) {
		refuseId=refuseId==null?"":refuseId;
		if(!refuseId.equals("")){
			String[] str=refuseId.split(",");
			List<OperatorRefuselist>  lists=new ArrayList<OperatorRefuselist>();
			String id="";
			OperatorRefuselist operatorRefuselist=null;
			for (int i = 0; i < str.length; i++) {
				operatorRefuselist=new OperatorRefuselist();
				id=str[i];
				operatorRefuselist.setId(id);
				lists.add(operatorRefuselist);
			}
			operatorRefuselistRepository.delete(lists);
		}
	}

	@Override
	public Map<String,Object> selectOperatorRefuselistPage(Integer page, Integer size,String keyName) {
		keyName=keyName==null?"":keyName;
		Map<String,Object> map=new HashMap<String,Object>();
		String jpql="select r "
				+ "from OperatorRefuselist r where r.attribution=:attribution and r.categoryName like :categoryName order by r.createDate desc";
		Query query = manager.createQuery(jpql).setParameter("attribution", 5).setParameter("categoryName", "%"+keyName+"%");
		int count=query.getResultList().size();
		List<OperatorRefuselist> list=query.setMaxResults(size)
				.setFirstResult(page*size)
				.getResultList();
		map.put("count", count);
		map.put("list", list);
		return map;
	}

	@Transactional
	public int updateRoomRefuselist(String refuseId, String categoryName) {
		String jpql = "UPDATE OperatorRefuselist p set p.categoryName=:categoryName where p.id =:refuseId"; 
		Query query = manager.createQuery(jpql); 
		query.setParameter("categoryName",categoryName); 
		query.setParameter("refuseId",refuseId); 
		int a=query.executeUpdate();
		return a;
	}

	@Override
	public List<ProvideSpacefacilities> selectSpacefacilitiesByIds(String ids) {
		ids=ids==null?"":ids;
		List<ProvideSpacefacilities> spacefacilities=null;
		if(!ids.equals("")){
			List<String> userList = Arrays.asList(ids.split(","));
			spacefacilities=provideSpacefacilitiesRepository.findByIdIn(userList);
		}
		return spacefacilities;
	}

	@Override
	public Map<String, Object> selectOperatorRefuseRecordPage(String username,String refusename,String startDate,String endDate,Integer page,Integer size) {
		username=username==null?"":username;
		Map<String,Object> map=new HashMap<String,Object>();
		String jpql="select r "
				+ "from OperatorRefuseRecord r where r.opchannel=3 and r.useraccountforcord like :username ";
		Date date1=null;
		Date date2=null;
		if(refusename!=null&&!refusename.equals("无")&&!refusename.equals("")){
			jpql+=" and r.reasonName=:reasonName ";
		}
		if(startDate!=null&&!startDate.equals("")){
			DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			try {
				date1=format.parse(startDate);
				jpql+=" and r.refuseTime >= :startDate ";
			} catch (ParseException e) {
				e.printStackTrace();
			}
		}
		if(endDate!=null&&!endDate.equals("")){
			DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			try {
				date2=format.parse(endDate);
				jpql+=" and r.refuseTime <= :endDate ";
			} catch (ParseException e) {
				e.printStackTrace();
			}
		}
		jpql+=" order by r.refuseTime desc";
		Query query = manager.createQuery(jpql).setParameter("username", username+"%");
		if(jpql.indexOf("and r.reasonName=:reasonName")>-1){
			query.setParameter("reasonName", refusename);
		}
		if(jpql.indexOf("and r.refuseTime >= :startDate")>-1){
			query.setParameter("startDate", date1);
		}
		if(jpql.indexOf("and r.refuseTime <= :endDate")>-1){
			query.setParameter("endDate", date2);
		}
		int count=query.getResultList().size();
		List<OperatorRefuseRecord> list=query.setMaxResults(size)
				.setFirstResult(page*size)
				.getResultList();
		map.put("count", count);
		map.put("list", list);
		return map;
	}

	@Override
	public ProvideRoom selectProvideRoomByroomCodes(String roomCodes) {
		// TODO Auto-generated method stub
		return operatorRoomRepository.findByroomCodes(roomCodes);
	}

	@Override
	public ProvideRoom selectProvideRoomByroomCodesAndcityId(String roomCodes,String id) {
		// TODO Auto-generated method stub
		return operatorRoomRepository.findByroomCodesAndcityId(roomCodes, id);
	}
	
	

}
